
//
//  NSObject+description.swift
//  12-04 通讯录
//
//  Created by 半缘君 on 15/12/9.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import Foundation
// MARK: - 获取所有属性并打印
extension NSObject {
    
    /// 获取所有属性
    ///
    /// - parameter clazz: 类名
    ///
    /// - returns: 属性数组
    func getProperties(clazz:AnyClass) -> [String] {
        var ivars:UnsafeMutablePointer<Ivar>
        var count:UInt32 = 0
        ivars = class_copyIvarList(clazz, &count)
    
        var keys = [String]()
        for i in 0 ..< Int(count) {
            let ivar = ivars[i]
            
            let varChar: UnsafePointer<Int8> = ivar_getName(ivar)
            
            let ivarName = NSString(UTF8String: varChar) as! String
            
            keys.append(ivarName)
            
        }
        return keys
    }
    /// 打印属性和值
    ///
    /// - parameter clazz: 类名
    ///
    /// - returns: 返回字典并打印 类似 OC
    func printClass (clazz:AnyClass) -> String {
        let keys = getProperties(clazz)
        return (dictionaryWithValuesForKeys(keys) as NSDictionary).description
    }
}
// MARK: - 解\归 档
extension NSObject {
    // 归档
    func encodeObj(obj: AnyObject, coder: NSCoder) {
        let properties = obj.getProperties(obj.classForCoder)
        for p in properties {
            coder.encodeObject(obj.valueForKey(p), forKey: p)
        }
    }
    
    // 解档
    func decodeObj(obj: AnyObject, coder: NSCoder) {
        let properties = obj.getProperties(obj.classForCoder)
        for p in properties {
            if let value = coder.decodeObjectForKey(p) {
//                print(p)
                obj.setValue(value, forKey: p)
            }
        }
//        print(obj)
    }
}